package org.glut.saltedfish.servlet;


import com.google.gson.Gson;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;
import org.glut.saltedfish.domain.Product;
import org.glut.saltedfish.mapper.ProductMapper;
import org.glut.saltedfish.service.ProductService;
import org.glut.saltedfish.utils.MyBatisUti;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/products")
public class ProductServlet extends HttpServlet {
    private ProductService productService;

    @Override
    public void init() throws ServletException {
        SqlSession sqlSession = MyBatisUti.getSqlSessionFactory().openSession();
        ProductMapper productMapper = sqlSession.getMapper(ProductMapper.class);
        productService = new ProductService(productMapper);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("application/json;charset=UTF-8");
        try {
            List<Product> products = productService.getAllProducts();
            Gson gson = new Gson();
            String json = gson.toJson(products);
            PrintWriter out = resp.getWriter();
            out.print(json);
            out.flush();
        } catch (Exception e) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            resp.getWriter().write("{\"error\":\"Internal Server Error\"}");
        }
    }

    // 删除 destroy() 方法，因为不再需要手动关闭
}